﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excell_On_Services.Models;
using System.ComponentModel;
using Excell_On_Services.ViewModels;

namespace Excell_On_Services.Controllers
{
    public class OrderController : Controller
    {
        public IEOSRepository Repository { get; set; }
        int ordersPerPage = 4;
        public OrderController()
            : this(new EFEOSRepository())
        {

        }

        public OrderController(IEOSRepository repository)
        {
            Repository = repository;
        }



        //
        // GET: /Order/
        [Authorize(Roles = "Manager,Employee,Administrators")]
        public ActionResult Index([DefaultValue(0)] int pageIndex)
        {
            //int departmentsPerPage = Configuration.Instance.PostPerPage;
            
            return ShowOrders(
                () => Repository.FindOrdersInPage(pageIndex, ordersPerPage),
                () => Repository.GetOrdersCount(),
                pageIndex, "Index", ordersPerPage,"Index"
                );
            

        }

        private ActionResult ShowOrders(Func<IEnumerable<OrderService>> filterFunc, Func<int> countFunc, int pageIndex, string actionName, int OrderPerPage,string strView)
        {
            var orders = filterFunc();
            var orderCount = countFunc();
            var model = new OrdersDisplayModel
            {
                Orders = orders,
                PagerModel = new PagerModel
                {
                    CurrentPageIndex = pageIndex,
                    ItemsPerPage = OrderPerPage,
                    TotalItems = orderCount,
                    PageUrlTemplate = Url.Action(actionName, new { pageIndex = PagerModel.PageSymbol })

                }
            };
            return View(strView, model);

        }

        //
        // GET: /Order/Details/5
        [Authorize(Roles = "Employee,Administrators")]
        public ActionResult Details(int id)
        {
            var order = Repository.FindOrderById(id);
            return View(order);
        }

        [Authorize(Roles = "Employee,Administrators")]
        public ActionResult EditStatusOrder(int id)
        {
            try
            {
                var order = Repository.FindOrderById(id);
                order.Status = !order.Status;
                Repository.CommitChanges();
                return View("Details",order);
            }
            catch (Exception)
            {

                throw;
            }
        }

        //
        // GET: /Order/Create
        [Authorize(Roles = "Employee,Administrators")]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Order/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Order/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Order/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Order/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Order/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult ApplyToSelected(OrdersDisplayModel model)
        {
            try
            {
                var orders =  Repository.FindOrdersInPage(model.PagerModel.CurrentPageIndex,ordersPerPage);
                foreach (var item in orders)
                {
                    foreach(var itemModel in model.Orders)
                    {
                        if (item.OrderID == itemModel.OrderID)
                        {
                            item.Status = item.Status;
                            break;
                        }
                    }
                }
                Repository.CommitChanges();
                return View("index", model.PagerModel.CurrentPageIndex);
            }
            catch (Exception ex)
            {

                return View("index", model.PagerModel.CurrentPageIndex);
            }
        }

        public ActionResult PaidPaymentOrder(int id)
        {
            try
            {
                OrderPayment payment = Repository.getPaymentById(id);
                if (payment != null)
                {
                    if (payment.DatePaid == null)
                    {
                        payment.DatePaid = DateTime.Now;
                        Repository.CommitChanges();
                        return RedirectToAction("Details", new { id = payment.OrderID});
                    }
                }
                return RedirectToAction("Details");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Details");
            }
            
        }

        [HttpPost]
        public ActionResult SearchOrders([DefaultValue(0)] int pageIndex,FormCollection collection)
        {
            try
            {
                int type = Convert.ToInt32(collection.Get("ddlType"));
                string strSearch="";

                switch (type)
                {
                    case 1:
                        strSearch = collection.Get("txtSearch");
                        break;
                    case 2:
                        strSearch = collection.Get("ddlCheck");
                        break;
                    case 3:
                        strSearch = collection.Get("tDate");
                        break;
                }
                   return ShowOrders(
                    () => Repository.SearchOrdersInPage(pageIndex, ordersPerPage, type, strSearch),
                    () => Repository.SearchOrdersInPage(pageIndex, ordersPerPage, type, strSearch).Count(),
                    pageIndex, "Index", ordersPerPage,"Index"
                    );
                
                
                
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                return Index(0);
            }
        }

        [Authorize(Roles="Client")]
        public ActionResult HistoryOrders([DefaultValue(0)] int pageIndex)
        {
            string username = User.Identity.Name;
            return ShowOrders(
                () => Repository.FindOrdersByClient(username,pageIndex, ordersPerPage),
                () => Repository.GetOrdersByClientCount(username),
                pageIndex, "HistoryOrders", ordersPerPage, "HistoryOrders"
                );
            
        }

        [Authorize(Roles="Client")]
        public ActionResult DetailsClient(int orderId)
        {
            string userName = User.Identity.Name;
            var order = Repository.FindOrderClientById(orderId, userName);
            return View(order);
        }


         
    }
}
